import { useContext, useEffect, useState, type FC } from "react";
import styles from "./index.module.less";
import LineContent from "./LineContent";
import {
  Badge,
  message,
  Spin,
  Tabs,
  TabsProps,
} from "@supcon/supcon-5t-design";
import spot from "@/assets/css/images/圆点.svg";
import { BigScreenContext } from "@/pages/BigScreen/context/BigScreenContext";
import { fetchParamInfo } from "@/pages/BigScreen/context/services/param";
import BGEmpty from "../../../BGEmpty";

const ParamContainer: FC = () => {
  const {
    currentKey,
    currentDevice,
    setCurrentDevice,
    paramJson,
    setParamJson,
  } = useContext(BigScreenContext);

  const items: TabsProps["items"] = [
    {
      key: "全部",
      label: "全部",
    },
    {
      key: "1#裂解炉",
      label: "1#裂解炉",
    },
    {
      key: "2#裂解炉",
      label: "2#裂解炉",
    },
    {
      key: "3#裂解炉",
      label: "3#裂解炉",
    },
    {
      key: "4#裂解炉",
      label: "4#裂解炉",
    },
    {
      key: "5#裂解炉",
      label: "5#裂解炉",
    },
  ];

  // const mockList: any[] = [
  //   {
  //     id: 32,
  //     createTime: "2025-04-24 16:26:10",
  //     updateTime: "2025-04-24 16:26:10",
  //     createBy: "admin",
  //     updateBy: "admin",
  //     workId: 5,
  //     variableName: "Auto-TAG52",
  //     variableUpper: "860",
  //     variableLow: "750",
  //     step: "1",
  //     variableDesc: "Auto-TAG52",
  //     configTagName: "Auto-TAG52",
  //     configTagDesc: "Auto-TAG52",
  //     isStart: 1,
  //   },
  //   {
  //     id: 33,
  //     createTime: "2025-04-24 16:26:10",
  //     updateTime: "2025-04-24 16:26:10",
  //     createBy: "admin",
  //     updateBy: "admin",
  //     workId: 5,
  //     variableName: "Auto-TAG51",
  //     variableUpper: "860",
  //     variableLow: "750",
  //     step: "1",
  //     variableDesc: "Auto-TAG51",
  //     configTagName: "Auto-TAG51",
  //     configTagDesc: "Auto-TAG51",
  //     configTagUnit: "L/HR",
  //     isStart: 1,
  //     unit: "L/HR",
  //   },
  // ];
  const [paramLoading, setParamLoading] = useState<boolean>(false);
  const [info, setInfo] = useState<any>({});

  const getData = async (key: any) => {
    setParamLoading(true);
    try {
      const queryDTO = {
        data: {
          nodeName: key,
        },
        requestBase: {
          page: "1-10",
          sort: "-createTime",
        },
      };
      const { status, content, msg } = await fetchParamInfo(queryDTO);
      if (status) {
        setParamJson(content);
      } else {
        message.error(msg);
      }
    } catch (error) {
      console.error("获取操作参数优化异常:", error);
      message.error("获取操作参数优化失败");
    } finally {
      setParamLoading(false);
    }
  };

  const onChange = (key: string) => {
    setCurrentDevice(key);
  };

  useEffect(() => {
    if (currentKey === "param") {
      setInfo(paramJson);
      paramJson?.factoryNodeName && setCurrentDevice(paramJson.factoryNodeName);
    }
  }, [currentKey, paramJson]);

  useEffect(() => {
    if (currentDevice) {
      getData(currentDevice);
    }
  }, [currentDevice]);

  return (
    <div className={styles["param-container"]}>
      <Spin spinning={paramLoading}>
        <div className={styles["param-container-tab"]}>
          <Tabs activeKey={currentDevice} items={items} onChange={onChange} />
        </div>
      </Spin>
      {/* 优化运行参数 */}
      {info.constructor === Object && Object.keys(info).length === 0 ? (
        <BGEmpty />
      ) : (
        <div className={styles["param-container-top-container"]}>
          <Spin spinning={paramLoading}>
            <div className={styles["param-container-top-section-wrapper"]}>
              <section className={styles["param-container-top-section"]}>
                <div className={styles["param-container-header"]}>
                  <div className={styles["param-container-header-title"]}>
                    <img src={spot} alt="spot"></img>
                    <div
                      className={styles["param-container-header-title-text"]}
                    >
                      优化运行基本信息
                    </div>
                  </div>
                  <div className={styles["param-container-header-status"]}>
                    <Badge
                      color={
                        info.optRunningStateDTO?.systemRunningState
                          ? "#00BF24"
                          : "#FF1001"
                      }
                      text={
                        <span style={{ color: "#FFFFFF", fontSize: "0.6rem" }}>
                          {info.optRunningStateDTO?.systemRunningState
                            ? "系统运行正常"
                            : "系统运行异常"}
                        </span>
                      }
                    />
                    <Badge
                      style={{ marginLeft: "1rem" }}
                      color={
                        info.optRunningStateDTO?.dataCommunicateState
                          ? "#00BF24"
                          : "#FF1001"
                      }
                      text={
                        <span style={{ color: "#FFFFFF", fontSize: "0.6rem" }}>
                          {info.optRunningStateDTO?.dataCommunicateState
                            ? "系统通讯正常"
                            : "系统通讯异常"}
                        </span>
                      }
                    />
                  </div>
                </div>
                <div className={styles["param-container-top-section-content"]}>
                  <div
                    className={
                      styles["param-container-top-section-content-row"]
                    }
                  >
                    <div
                      className={
                        styles["param-container-top-section-content-row-left"]
                      }
                    >
                      <span
                        className={
                          styles["param-container-top-section-content-title"]
                        }
                      >
                        优化主体
                      </span>
                      {info.optRunningParamsDTO?.optTarget || "--"}
                    </div>
                    <div
                      className={
                        styles["param-container-top-section-content-row-right"]
                      }
                    >
                      <span
                        className={
                          styles["param-container-top-section-content-title"]
                        }
                      >
                        装置运行状态
                      </span>
                      <span
                        style={{
                          color: info.optRunningParamsDTO?.runningState
                            ? "#00ff00"
                            : "#FF1001",
                        }}
                      >
                        {info.optRunningParamsDTO?.runningState
                          ? "稳态"
                          : "非稳态"}
                      </span>
                    </div>
                  </div>
                  <div
                    className={
                      styles["param-container-top-section-content-row"]
                    }
                  >
                    <div
                      className={
                        styles["param-container-top-section-content-row-left"]
                      }
                    >
                      <span
                        className={
                          styles["param-container-top-section-content-title"]
                        }
                      >
                        优化周期
                      </span>
                      {info.optRunningParamsDTO?.optPeriod
                        ? `${info.optRunningParamsDTO?.optPeriod}分钟`
                        : "--"}
                    </div>
                    <div
                      className={
                        styles["param-container-top-section-content-row-right"]
                      }
                    >
                      <span
                        className={
                          styles["param-container-top-section-content-title"]
                        }
                      >
                        最后输出时间
                      </span>
                      {info.optRunningParamsDTO?.lastOptTime || "--"}
                    </div>
                  </div>
                  <div
                    className={
                      styles["param-container-top-section-content-row"]
                    }
                  >
                    <div
                      className={
                        styles["param-container-top-section-content-row-left"]
                      }
                    >
                      <span
                        className={
                          styles["param-container-top-section-content-title"]
                        }
                      >
                        累计优化
                      </span>
                      {info.optRunningParamsDTO?.optCount
                        ? `${info.optRunningParamsDTO?.optCount}次`
                        : "--"}
                    </div>
                    <div
                      className={
                        styles["param-container-top-section-content-row-right"]
                      }
                    >
                      <span
                        className={
                          styles["param-container-top-section-content-title"]
                        }
                      >
                        最后执行时间
                      </span>
                      {info.optRunningParamsDTO?.lastExecTime || "--"}
                    </div>
                  </div>
                </div>
              </section>

              {/* 优化运行数据 */}
              <section style={{ marginBottom: "1rem" }}>
                <div className={styles["param-container-header"]}>
                  <div className={styles["param-container-header-title"]}>
                    <img src={spot} alt="spot"></img>
                    <div
                      className={styles["param-container-header-title-text"]}
                    >
                      优化控制变量
                    </div>
                  </div>
                </div>
                <table className={styles["param-container-table"]}>
                  <thead>
                    <tr>
                      <th
                        className={styles["param-container-table-th"]}
                        style={{ width: "1.5rem", minWidth: 24 }}
                      >
                        序号
                      </th>
                      <th
                        className={styles["param-container-table-th"]}
                        style={{ width: "9rem", minWidth: 160 }}
                      >
                        操作变量名
                      </th>
                      <th className={styles["param-container-table-th"]}>
                        当前值
                      </th>
                      <th className={styles["param-container-table-th"]}>
                        上限值
                      </th>
                      <th className={styles["param-container-table-th"]}>
                        下限值
                      </th>
                      <th
                        className={styles["param-container-table-th"]}
                        style={{ minWidth: 48 }}
                      >
                        优化目标
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {info.optCtrlParamsDTOList &&
                      info.optCtrlParamsDTOList.map((record, index) => (
                        <tr key={record.id}>
                          <td
                            className={styles["param-container-table-td"]}
                            style={{ width: "1.5rem" }}
                          >
                            {index + 1}
                          </td>
                          <td
                            className={styles["param-container-table-td"]}
                            style={{ width: "9rem", minWidth: 160 }}
                          >
                            {record.variableName || "--"}
                          </td>
                          <td
                            className={styles["param-container-table-number"]}
                          >
                            {record.algCurValue || "--"}
                          </td>
                          <td
                            className={styles["param-container-table-number"]}
                          >
                            {record.variableUpper || "--"}
                          </td>
                          <td
                            className={styles["param-container-table-number"]}
                          >
                            {record.variableLow || "--"}
                          </td>
                          <td
                            className={styles["param-container-table-number"]}
                          >
                            {record.optValue || "--"}
                          </td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </section>

              {/* 乙烯收率跟踪 */}
              <section>
                <div className={styles["param-container-header"]}>
                  <div className={styles["param-container-header-title"]}>
                    <img src={spot} alt="spot"></img>
                    <div
                      className={styles["param-container-header-title-text"]}
                    >
                      乙烯收率跟踪
                    </div>
                  </div>
                </div>
                <LineContent
                  record={info.optWorkResults}
                  showTarget={info.optRunningParamsDTO?.runningState === "1"}
                ></LineContent>
                {/* <TestChart
            record={{}}
            showTarget={info.optRunningParamsDTO?.runningState}
          ></TestChart> */}
              </section>
            </div>
          </Spin>
        </div>
      )}
    </div>
  );
};

export default ParamContainer;
